from socketserver import BaseRequestHandler, ThreadingTCPServer
from app import app
from flask_sqlalchemy import SQLAlchemy
from models import PersonNumber, Camera
from exts import get_time

# app.app_context().push()
db = SQLAlchemy(app)


class Handler(BaseRequestHandler):

    def handle(self) -> None:
        address, pid = self.client_address
        print(f'{address} connected!')
        while True:
            data = self.request.recv(1024)
            if len(data) <= 0:
                print("close!")
                break
            data_dict = eval(data.decode())
            print(f'receive data: {data_dict}')

            # 存入数据库
            camera = db.session.query(Camera).filter(Camera.ipv4 == data_dict.get("ip")).first()
            if camera is None:
                camera = Camera(ipv4=data_dict.get("ip"),
                                place="未知",
                                state="未加入系统中的摄像头")
            pn = PersonNumber(number_in_a_frame=data_dict.get("number_in_a_frame"),
                              number_cumulative=data_dict.get("number_cumulative"),
                              time=get_time(),
                              camera=camera,
                              warnings=data_dict.get("warnings"))

            db.session.add(pn)
            db.session.commit()


if __name__ == '__main__':
    server = ThreadingTCPServer(('0.0.0.0', 5002), Handler)
    print("Listening")
    server.serve_forever()
